import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mirror/AppStyle.dart';
import 'package:mirror/CommonButton.dart';
import 'package:mirror/CommonLoading.dart';
import 'package:mirror/Util.dart';
import 'package:mirror/api/UserApi.dart';
import 'package:mirror/page/RegisterPage.dart';
import 'package:mirror/page/home/MainPage.dart';
import 'package:mirror/service/NetworkService.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  bool showAccountClear = false;
  var accountController = TextEditingController();
  var passwordController = TextEditingController();
  bool hidePassword = true;

  @override
  void initState() {
    super.initState();
    accountController.text = "";
    passwordController.text = "";
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
        statusBarColor: Constant.mainColor,
        statusBarIconBrightness: Brightness.light));
    return Scaffold(
      appBar: AppBar(
        title: const Text("登录"),
      ),
      body: SingleChildScrollView(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            SizedBox(
              height: MediaQuery.of(context).size.height * 0.1,
            ),
            const Text(
              "欢迎登录",
            ),
            const SizedBox(
              height: 10,
            ),
            const Text(
              "MIRROR ART",
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
            const SizedBox(
              height: 20,
            ),
            Container(
              margin: const EdgeInsets.all(10),
              padding: const EdgeInsets.all(20),
              decoration: BoxDecoration(
                  borderRadius: Constant.borderRadius,
                  color: Colors.white,
                  boxShadow: Constant.boxShadow),
              child: Column(
                children: [
                  TextField(
                    controller: accountController,
                    onChanged: (s) {
                      setState(() {
                        showAccountClear = s.isNotEmpty;
                      });
                    },
                    keyboardType: TextInputType.number,
                    decoration: InputDecoration(
                        prefixIcon: const Icon(Icons.account_box_outlined),
                        hintText: "请输入手机号或邮箱",
                        suffix: InkWell(
                            onTap: () {
                              if (showAccountClear) {
                                accountController.clear();
                                setState(() {
                                  showAccountClear = false;
                                });
                              }
                            },
                            child: showAccountClear
                                ? const Padding(
                                    padding: EdgeInsets.all(8.0),
                                    child: Icon(Icons.clear),
                                  )
                                : const SizedBox(
                                    width: 0,
                                    height: 0,
                                  ))),
                  ),
                  TextField(
                    inputFormatters: Constant.inputFormatterPassword,
                    controller: passwordController,
                    obscureText: hidePassword,
                    decoration: InputDecoration(
                        prefixIcon: const Icon(Icons.password),
                        hintText: "请输入密码",
                        suffix: InkWell(
                            onTap: () {
                              setState(() {
                                hidePassword = !hidePassword;
                              });
                            },
                            child: hidePassword
                                ? const Padding(
                                    padding: EdgeInsets.all(8.0),
                                    child: Icon(Icons.remove_red_eye_outlined),
                                  )
                                : const Padding(
                                    padding: EdgeInsets.all(8.0),
                                    child: Icon(Icons.remove_red_eye),
                                  ))),
                  ),
                ],
              ),
            ),
            Padding(
                padding: const EdgeInsets.only(top: 20),
                child: CommonButton(
                  title: "登录",
                  onTap: () async {
                    login(
                        phone: accountController.text,
                        password: passwordController.text);
                  },
                )),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 40),
              child: InkWell(
                onTap: () async {
                  var res = await Navigator.push(context,
                      MaterialPageRoute(builder: (c) => const RegisterPage()));
                  if (res != null) {
                    login(phone: res['phone'], password: res["password"]);
                  }
                },
                child: Padding(
                  padding: const EdgeInsets.all(10),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      const Text("还没有账号？"),
                      Text(
                        "去注册>",
                        style: TextStyle(
                            fontWeight: FontWeight.bold,
                            color: Constant.mainColor),
                      ),
                    ],
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  Future<void> login({required phone, required password}) async {
    if (accountController.text.isEmpty) {
      Util.toast("请输入账号");
      return;
    }
    bool isEmail = accountController.text.contains("@");
    if (!isEmail && accountController.text.length != 11) {
      Util.toast("请输入正确的手机号");
      return;
    }
    if (passwordController.text.isEmpty) {
      Util.toast("请输入密码");
      return;
    }
    try {
      CommonLoading.show();
      var navigator = Navigator.of(context);
      if (isEmail) {
        await UserApi.login(
            phone: "",
            password: passwordController.text,
            email: accountController.text);
      } else {
        await UserApi.login(
            phone: accountController.text,
            password: passwordController.text,
            email: '');
      }

      CommonLoading.hide();
      navigator
          .pushReplacement(MaterialPageRoute(builder: (c) => const MainPage()));
    } catch (e) {
      CommonLoading.hide();
      if (e is RequestError) {
        Util.toast(e.message);
      } else {
        print(e);
      }
    }
  }
}
